<?php

namespace frontend\controllers;

use Yii;
use frontend\models\PnKho;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Html;
/**
 * KhoController implements the CRUD actions for PnKho model.
 */
class KhoController extends Controller
{
    public function behaviors()
	{
		return [
			'verbs' => [
				 'class' => VerbFilter::className(),
				 'actions' => [
					  'delete' => ['post'],
				 ],
			],
		];
	}

    /**
     * Lists all PnKho models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => PnKho::find(),
				'sort'=> [
					'defaultOrder' => ['so_ctu' => SORT_DESC]
				],
				'pagination' => [
					'pageSize' => 5,
				],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }
	
	/**
     * Lists all PnKho models.
     * @return mixed
     */
	public function actionTraCuu(){
		return $this->actionIndex();
	}
	
    /**
     * Displays a single PnKho model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new PnKho model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
   public function actionCreate(){
		$model = new PnKho();
		if ($model->load(Yii::$app->request->post())) {
			$model->uid	=	Yii::$app->user->identity->id;
         $model->ma_ctu	=	'NK/'.date("m/Y");
			if($model->save())
				return $this->redirect(['view', 'id' => $model->id]);
      } else {
			return $this->render('create', [
				'model' => $model,
         ]);
      }
   }

    /**
     * Updates an existing PnKho model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load($data = Yii::$app->request->post())) {
            $model->ngay_hdon	= strtotime(str_replace("/","-",$model->ngay_hdon));
				$model->tien_hang = (int)str_replace(" ","",$data['PnKho']['tien_hang']);
				$model->tien_thue = (int)str_replace(" ","",$data['PnKho']['tien_thue']);
				$model->tien_thanh_toan = (int)str_replace(" ","",$data['PnKho']['tien_thanh_toan']);
				$model->nguoi_sua	=	Yii::$app->user->identity->id;
				$model->ngay_sua	=	strtotime("now");
				//
				if($model->save()){
					\frontend\models\PnKhoDetail::deleteAll(['pid'=>$model->id]);
					$cols = ['pid','ma_hang','ten_hang','dvt','sl_ycau','sl_thuc','don_gia','thue_suat','tien_thue','thanh_tien','tk_no','tk_co','order'];
					$vals = [];
					$tkno = [];
					// echo '<pre>';
					// print_r($data);die;
					$order = 1;
					foreach($data['PnKhoDetail'] as $obj){
						if(!in_array($obj['tk_no'],$tkno) && $obj['tk_co'] != $tkno[$obj['tk_no']]){
							$tkno[$obj['tk_no']] = $obj['tk_co'];
							$vals[] = [$model->id,$obj['ma_hang'],$obj['ten_hang'],$obj['dvt'],floatval($obj['sl_ycau']),floatval($obj['sl_thuc']),intval(str_replace(" ", "", $obj['don_gia'])),floatval($obj['thue_suat']),intval(str_replace(" ", "", $obj['tien_thue'])),intval(str_replace(" ", "", $obj['thanh_tien'])),$obj['tk_no'],$obj['tk_co'],$order++];
						}
					}
					$tmp = Yii::$app->db->createCommand()->batchInsert(\frontend\models\PnKhoDetail::tableName(),$cols,$vals)->execute();
					return $this->redirect(['view', 'id' => $model->id]);
				}
				// $model->save();
				// return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing PnKho model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
   public function actionDelete($id){
		$this->findModel($id)->delete();
		return $this->redirect(['index']);
   }
	
	public function actionNccInfo(){
		// var_dump(Yii::$app->request->isAjax);die;
		if(!Yii::$app->request->isAjax || !Yii::$app->request->isPost)
			$this->goHome();
		else{
			$id = Yii::$app->request->get('id');
			$model	= \frontend\models\DmNhaCungCap::findOne(['id' => $id]);
			Yii::$app->response->format = 'json';
			header('Content-type: application/json');
			echo \yii\helpers\Json::encode([
				'status'	=>	true,
				'data'	=>	[
					'ten'	=>	$model->ten,
					'mst'	=>	$model->mst
				]
			]);
			exit;
		}
	}
	
	/**
	**
	**
	*/
	public function actionAddDetail(){
		// var_dump(Yii::$app->request->isAjax);die;
		if(!Yii::$app->request->isAjax || !Yii::$app->request->isPost)
			$this->goHome();
		else{
			$type = Yii::$app->request->get('type');
			$row = (int)Yii::$app->request->get('row');
			$row++;
			if($type === "input"){
				ob_start();
		?>
			<tr>
				<td><input type="checkbox" class="check" style="margin-top:12px"></td>
				<td>
					<?php $name = "PnKhoDetail[$row][ma_hang]";?>
					<?=Html::dropDownList($name,false,(new PnKho)->getDmHangHoaByNhom(),[
						'class'	=>	'form-control',
						'onchange'	=>	"kho.nhap.hangHoaInfo('".Yii::$app->urlManager->createUrl('kho/hang-hoa-info?id=')."'+$(this).val(), this, event)",
					])?>
				</td>
				<td>
					<input class="form-control ten-hang" name="PnKhoDetail[<?=$row?>][ten_hang]" value=""/>
				</td>
				<td>
					<input type="text" class="form-control dvt" name="PnKhoDetail[<?=$row?>][dvt]">
				</td>
				<td>
					<input type="text" class="form-control text-right sl-ycau" name="PnKhoDetail[<?=$row?>][sl_ycau]" onfocus="yii.number_focus(this)" onblur="yii.float_number_blur(this)">
				</td>
				<td>
					<input type="text" class="form-control text-right sl-thuc" name="PnKhoDetail[<?=$row?>][sl_thuc]" onfocus="yii.number_focus(this)" onblur="yii.float_number_blur(this)" onchange="kho.nhap.tinhTien(this,event)">
				</td>
				<td>
					<input type="text" class="form-control text-right don-gia" name="PnKhoDetail[<?=$row?>][don_gia]" onfocus="yii.number_focus(this)" onblur="yii.number_blur(this)" onchange="kho.nhap.tinhTien(this,event)">
				</td>
				<td>
					<input type="text" class="form-control text-right thanh-tien" name="PnKhoDetail[<?=$row?>][thanh_tien]" onfocus="yii.number_focus(this)" onblur="yii.number_blur(this)" readonly="true">
				</td>
				<td>
					<?=Html::dropDownList("PnKhoDetail[$row][thue_suat]",false,(new PnKho)->getDmThueSuat(),[
						'class'=>"thue-suat form-control",
						'onchange'	=>	"kho.nhap.tinhThue(this);kho.nhap.tinhTien(this,event)"
					])?>
				</td>	
				<td>
					<input type="text" class="form-control text-right tien-thue" name="PnKhoDetail[<?=$row?>][tien_thue]" readonly="true">
				</td>
				<td>
					<?=Html::dropDownList("PnKhoDetail[$row][tk_no]",false,(new PnKho)->getTkNoList(),['class'=>"tkNo form-control"])?>
				</td>
				<td>
					<?=Html::dropDownList("PnKhoDetail[$row][tk_co]",false,(new PnKho)->getTkCoList(),['class'=>"tkCo form-control"])?>
				</td>	
			</tr>
		<?php
		}
			$html = ob_get_clean();
			// Yii::$app->response->format = 'json';
			header('Content-type: text/html');
			echo $html;
			exit;
		}
	}
	
	public function actionHangHoaInfo(){
		// var_dump(Yii::$app->request->isAjax);die;
		if(!Yii::$app->request->isAjax || !Yii::$app->request->isPost)
			$this->goHome();
		else{
			$id = Yii::$app->request->get('id');
			// $model	= \frontend\models\DmHangHoa::find(['id' => $id])->joinWith('');
			$sql = "SELECT hh.*,dv.ten ten_dvt
				FROM dm_hang_hoa hh 
				JOIN dm_dvt dv  ON dv.id = hh.dvt_id
				WHERE hh.trang_thai = 'Y' AND hh.ma IN ('$id')";			
			$data =	\frontend\models\DmHangHoa::findBySql($sql)->asArray()->one();
			Yii::$app->response->format = 'json';
			header('Content-type: application/json');
			echo \yii\helpers\Json::encode([
				'status'	=>	true,
				'data'	=>	[
					'ten'	=>	$data['ten'],
					'tenDvt'	=>	$data['ten_dvt']
				]
			]);
			exit;
		}
	}
	
    /**
     * Finds the PnKho model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PnKho the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PnKho::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	
}
